# -*- coding: utf-8 -*-
import json
import base64
from werkzeug.urls import url_decode
from odoo.http import content_disposition, request, route, serialize_exception as _serialize_exception
from odoo.tools import html_escape, safe_eval, time
from odoo.addons.web.controllers.report import ReportController
from odoo import fields


class XlsxReportController(ReportController):

    @route()
    def report_routes(self, reportname, docids=None, converter=None, **data):
        if converter == "xlsx-jinja":
            report = request.env["ir.actions.report"]._get_report_from_name(reportname)
            context = dict(request.env.context)

            # --- 檢查是否存在快取 ---
            config_id = report.jinja_id.id
            cache = None
            config = None
            month_key = fields.Date.today().strftime("%Y-%m")
            if config_id:
                config = request.env["xlsx.report.config"].sudo().browse(int(config_id))
                if config and config.default_date_range and config.date_range_mode == 'months':
                    cache = request.env["xlsx.report.cache"].sudo().search([
                        ("config_id", "=", config.id),
                        ("month_key", "=", month_key),
                    ], limit=1)

            # 若快取存在 → 直接返回
            if cache:
                filename = cache.file_name or f"{reportname}.xlsx"
                content_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                httpheaders = [
                    ("Content-Type", content_type),
                    ("X-File-Name", filename),
                    ("Content-Disposition", content_disposition(filename)),
                ]
                return request.make_response(base64.b64decode(cache.file_data), headers=httpheaders)

            # --- 若無快取則正常生成 ---
            if docids:
                docids = [int(i) for i in docids.split(",")]
            if data.get("options"):
                data.update(json.loads(data.pop("options")))
            if data.get("context"):
                data["context"] = json.loads(data["context"])
                context.update(data["context"])

            xlsx_files, file_type = report.with_context(**context)._render_jinja_xlsx(reportname, docids, data=data)
            extension = "zip" if file_type == "zip" else "xlsx"
            final_report_name = reportname

            if docids and len(docids) == 1 and report.print_report_name:
                try:
                    obj = request.env[report.model].browse(docids[0])
                    final_report_name = safe_eval(report.print_report_name, {"object": obj, "time": time})
                except Exception:
                    pass

            filename = f"{final_report_name}.{extension}"

            # --- 保存快取 ---
            if config and config.default_date_range and config.date_range_mode == 'months':
                request.env["xlsx.report.cache"].sudo().create({
                    "config_id": config.id,
                    "month_key": month_key,
                    "file_data": base64.b64encode(xlsx_files),
                    "file_name": filename,
                    "record_count": len(docids or []),
                })

            content_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            if file_type == "zip":
                content_type = "application/zip"

            httpheaders = [
                ("Content-Type", content_type),
                ("X-File-Name", filename),
                ("Content-Disposition", content_disposition(filename)),
            ]
            return request.make_response(xlsx_files, headers=httpheaders)

        return super().report_routes(reportname, docids, converter, **data)

    @route()
    def report_download(self, data, context=None, token=None):
        requestcontent = json.loads(data)
        url, report_type = requestcontent[0], requestcontent[1]
        try:
            if report_type == "xlsx-jinja":
                reportname = url.split("/report/xlsx-jinja/")[1].split("?")[0]
                docids = None
                if "/" in reportname:
                    reportname, docids = reportname.split("/")

                if docids:
                    response = self.report_routes(reportname, docids=docids, converter="xlsx-jinja", context=context)
                else:
                    data = dict(url_decode(url.split("?")[1]).items())
                    if "context" in data:
                        context, data_context = json.loads(context or "{}"), json.loads(data.pop("context"))
                        context = json.dumps({**context, **data_context})
                    response = self.report_routes(reportname, docids=docids, converter="xlsx-jinja", context=context, **data)

                filename = response.headers.get("X-File-Name") or f"{reportname}.xlsx"
                if not response.headers.get("Content-Disposition"):
                    response.headers.add("Content-Disposition", content_disposition(filename))
                return response
            else:
                return super().report_download(data, context=context, token=token)
        except Exception as e:
            se = _serialize_exception(e)
            error = {"code": 200, "message": "Odoo Server Error", "data": se}
            return request.make_response(html_escape(json.dumps(error)))
